<?php
class Pagination {
    private $conn;

    public function __construct(PDO $conn) {
        $this->conn = $conn;
    }

    /**
     * 分页处理
     * @param string $query 主查询SQL
     * @param array $params 主查询参数
     * @param string $table 表名(用于计算总数)
     * @param string $where WHERE条件(不含WHERE关键字)
     * @param array $whereParams WHERE条件参数
     * @return array 分页结果
     */
    public function paginate(
        string $query,
        array $params,
        string $table,
        string $where = '1=1',
        array $whereParams = []
    ): array {
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(100, max(2, intval($_GET['pageSize'] ?? 10)));
        $offset = ($page - 1) * $pageSize;

        // 获取总数
        $countStmt = $this->conn->prepare("SELECT COUNT(*) FROM {$table} WHERE {$where}");
        $countStmt->execute($whereParams);
        $total = $countStmt->fetchColumn();

        // 获取数据
        $dataStmt = $this->conn->prepare($query . " LIMIT :offset, :limit");
        foreach ($params as $key => $value) {
            $dataStmt->bindValue($key, $value);
        }
        $dataStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $dataStmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        $dataStmt->execute();
        $data = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

        return [
            'list' => $data,
            'pagination' => [
                'total' => $total,
                'page' => $page,
                'pageSize' => $pageSize,
                'totalPages' => ceil($total / $pageSize)
            ]
        ];
    }
}